package com.wealth.sms.service.impl;

import java.util.ArrayList;
import java.util.Collection;

import org.joda.time.DateTime;
import org.joda.time.Seconds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;

import com.wealth.sms.entity.MessageChannel;
import com.wealth.sms.entity.MessageRecord;
import com.wealth.sms.repository.MessageChannelDao;
import com.wealth.sms.repository.MessageRecordDao;
import com.wealth.sms.service.IMessageRecordService;

import iaas.persistence.DynamicSpecifications;
import iaas.persistence.SearchFilter;
import iaas.persistence.SearchFilter.Operator;
import iaas.service.impl.BaseServiceImpl;

/**
 * 
 * @author chan
 */
@Component
public class MessageRecordServiceImpl extends BaseServiceImpl<MessageRecord> implements IMessageRecordService {

	@Autowired
	private MessageRecordDao recordDao;
	@Autowired
	private MessageChannelDao messageChannelDao;
	
	/** ------------------------------- 扩展  ------------------------------*/
	
	/**
	 * 计算当前时间和最新一条短信记录的时间差
	 * -1 表示没有任何一条记录
	 */
	public int calculateInterval(Long corpid, String mobile) throws Exception{
		MessageRecord latestRecord = recordDao.findTopByCorpIdAndMobileOrderByCreateTimeDesc(corpid, mobile);
		if(latestRecord==null){
			return -1;
		}
		DateTime start = new DateTime(latestRecord.getCreateTime());
		DateTime end = new DateTime();
		int diff = Seconds.secondsBetween(start,end).getSeconds();
		return diff;
	}

	/**
	 * 判断是否在发送最小间隔内 60s
	 * ps：短信通道是否停用，交给控制器处理
	 */
	@Override
	public boolean isMinimumInterval(Long corpid, String mobile) throws Exception{
		//短信通道
		MessageChannel channel = messageChannelDao.findByCorpId(corpid); 
		//获得发送最小间隔时间，当前时间和最新一条短信记录的时间差
		int minimumInterval = channel.getMinimumInterval();
		int diff = calculateInterval(corpid, mobile);
		System.out.println("最小间隔diff="+diff);
		return (diff>=0 && diff<=minimumInterval)?true:false;
	}
	
	/**
	 * 判断是否,达到预警线
	 */
	@Override
	public boolean isReachWaringLine(Long corpid) throws Exception{
		//获取警戒线，每日最大发送短信数量
		MessageChannel channel = messageChannelDao.findByCorpId(corpid); 
		long warningLine = channel.getWarningLine().longValue();
		
		Collection<SearchFilter> filters = new ArrayList<SearchFilter>();
		filters.add(new SearchFilter("corp.id", Operator.EQ, corpid));
		filters.add(new SearchFilter("createTime", Operator.GE, new DateTime().toString("yyyy-MM-dd")));
		filters.add(new SearchFilter("createTime", Operator.LE, new DateTime().toString("yyyy-MM-dd")));
		Specification<MessageRecord> spec = DynamicSpecifications.bySearchFilter(filters, MessageRecord.class);
		long sendCount = recordDao.count(spec);
		
		return (sendCount>=warningLine)?true:false;
	}
}


